package com.example.a700.myapplication_android;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends AppCompatActivity {
    private ImageView image;
    private Button button;
    private int[] imgs={R.drawable.one,R.drawable.two,R.drawable.three,R.drawable.four,R.drawable.five };
    private int index=0;
    private Handler handler;
    private final int message_change=1001;
    //是否处于暂停状态
    private boolean isPause=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        handler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if(message.what==message_change){

                     index=(index+1)%imgs.length;
                    image.setImageResource(imgs[index]);
                    return true;

                }
                return false;
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {

                while (true){

                    try{

                        Thread.sleep(2000);
                    }
                    catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    if(isPause) {
                        Message message = new Message();
                        message.what = message_change;
                        handler.sendMessage(message);
                        Log.i("MainActivity", "send change message");

                    }
                }

            }

        }).start();


        image=findViewById(R.id.image);
        button=findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view) {

                isPause=!isPause;

            }
        } );

    }
}
